<?php
declare (strict_types = 1);

namespace app\middleware\admin;
use app\repositories\contracts\MenuInterface;
use app\repositories\contracts\RootGroupInterface;
use think\facade\Route;
use think\facade\Session;
/***
 * Class PromiseAuth
 * @package app\middleware\admin
 * @Author Vee7
 * @Date 2021/12/17
 * @Time 9:17
 * @Description 后台权限验证中间件
 */
class PromiseAuth
{
    protected $menu;
    protected $group;

    public function __construct(MenuInterface $menu,RootGroupInterface $group)
    {
        $this->menu = $menu;
        $this->group = $group;
    }

    public function handle($request, \Closure $next)
    {
        //获取当前登录用户
        $rootData = $request->rootData;
        if($rootData['status'] === 0){
            session('RootData', null);
            return redirect('/admin/login/')->with('errorMsg','您的账户已被禁用');
        }

        //根据菜单路由规则拼接当前路由
        $menu_route = '/'.app('http')->getName().'/'.$request->pathinfo();
        if($menu_route === '/admin/'){
            $menu_route = '/admin/index/index';
        }else if(substr_count($menu_route,'/') === 2){
            $menu_route = $menu_route.'/index';
        }
        if(substr_count($menu_route,'/') > 3){
            $menu_route_arr = explode('/',$menu_route);
            $menu_route = '/'.$menu_route_arr[1].'/'.$menu_route_arr[2].'/'.$menu_route_arr[3];
        }
        $menu_route = strtolower($menu_route);
//        dump($menu_route);
        //获取当前路由的菜单id
        $menuData = $this->menu->getMenuInfo($menu_route);
        //不存在于菜单的路由不进行验证
        if($menuData === null){
            return $next($request);
        }
        $menuData = $menuData->toArray();
        //判断当前请求的菜单状态是否开启
        if($menuData['status'] == 0){
            return redirect('/admin/root_group/NoPromise/errorMsg/很抱歉，当前模块被禁用');
        }


        //获取当前用户的菜单权限,转为数组
        $groupData = $this->group->getRootGroupData($rootData['group_id']);
        $promise_menu_id = explode(',',$groupData['promise_menu_id']);
        //判断该用户请求的当前路由所属菜单id是否有权限
        $result = in_array($menuData['id'],$promise_menu_id);
//        dump('当前访问ID：'.$menuData['id'].'-----可访问ID：'.$groupData['allow_menu_id'].'-----结果：'.$result);
        if(!$result){
            return redirect('/admin/root_group/NoPromise/errorMsg/很抱歉，您没有访问权限');
        }
        $request->promise_menu_id = $promise_menu_id;
        //dump($request->promise_menu_id);

        //将当前路由菜单数据也传递，用于给控制器基类实现面包屑导航
        $request->menuData = $menuData;
        return $next($request);
    }
}
